//Date: 2023-11-23 21:09:28
//LastEditors: jie zhengjie_liang@qq.com
//LastEditTime: 2023-11-26 00:20:46
//FilePath: /photowall/main/router/staticfile.go

package router

import (
	"log/slog"
	"path/filepath"
	"photowall/pkg/config"
	"photowall/pkg/objdef"
	"photowall/pkg/options"
	"strings"

	"github.com/gin-gonic/gin"
)

func init() {
	router := GetMainRouter()

	router.GET("/staticfile/uploadfile/", uploadFile)
	router.POST("/staticfile/add/", postFileAdd)
	router.GET("/staticfile/:file_md5", postFileGet)
	router.POST("/staticfile/delete/:file_md5", postFileDel)
}

func uploadFile(c *gin.Context) {
	slog.Info("upload act")
	// filePath := "./main/src/static/upload.html"
	filePath := "/root/code/src/photowall/web/static/upload.html"

	c.File(filePath)
}

func postFileAdd(c *gin.Context) {
	fileHeader, err := c.FormFile("file")
	if err != nil {
		c.JSON(500, gin.H{
			"msg": "upload failed",
		})
		return
	}

	md5Str := options.GetMD5ByMultipartHeader(fileHeader)
	if md5Str == "" {
		c.JSON(500, gin.H{
			"msg": "can not phrase file md5",
		})

		return
	}

	var fileMetadata objdef.FileMetadata

	fileName := fileHeader.Filename
	fileStrArr := strings.Split(fileName, ".")
	fileType := fileStrArr[len(fileStrArr)-1]

	fileMetadata.FileMD5 = md5Str
	fileMetadata.FileType = fileType
	fileMetadata.Optimized = false
	fileMetadata.CitationCount = 1

	options.AsyncAddStaticFile(&fileMetadata, c)

	c.JSON(200, gin.H{
		"image": md5Str,
	})
}

func postFileGet(c *gin.Context) {
	md5Str := c.Param("file_md5")

	if len(md5Str) == 0 {
		c.JSON(400, gin.H{})
		return
	}

	available, _ := options.CheckFileIsAvailable(md5Str)

	if !available {
		c.JSON(400, gin.H{
			"msg": "empty file",
		})
		return
	}

	filePath := filepath.Join(config.GetConfig().FileSaveConfig.ImageConfig.ImageSavePath,
		md5Str)
	c.File(filePath)
}

func postFileDel(c *gin.Context) {
	md5Str := c.Param("file_md5")

	if len(md5Str) == 0 {
		c.JSON(400, gin.H{})
		return
	}

	go options.AsyncDeleteFile(md5Str)

	c.JSON(200, gin.H{
		"msg": "ok",
	})
}
